<template>
    <div class="step-question">
      <div class="question-container" :class="{ embed: props.embed }">
        <div class="web-header">
          <div class="title">一键出题</div>
          <div class="actions">
            <div class="clear-button" @click="clearAll">
              <Icon name="delete-o" size="16" />
              <span>清空</span>
            </div>
          </div>
        </div>
        
        <div class="question-content">
          <!-- 左侧：上传区域 -->
          <div class="input-section">
            <div class="section-header">
              <h3>上传文档</h3>
            </div>
            
            <div class="upload-section">
              <!-- 自定义文件上传组件 -->
              <div v-if="!uploadedFile" class="custom-upload">
                <div class="upload-area" @click="triggerFileInput">
                  <Icon name="plus" size="40" color="#1989fa" />
                  <p>点击上传文件</p>
                  <span>支持 PDF、Word、PPT、TXT 等格式</span>
                  <span class="size-limit">文件大小限制：50MB</span>
                </div>
                <input 
                  id="file-input"
                  type="file" 
                  accept=".pdf,.doc,.docx,.txt,.ppt,.pptx"
                  style="display: none"
                  @change="handleFileSelect"
                />
              </div>
              
              <div v-else class="uploaded-file">
                <div class="file-info">
                  <Icon name="description" size="32" color="#1989fa" />
                  <div class="file-details">
                    <div class="file-name">{{ uploadedFile.name }}</div>
                    <div class="file-meta">
                      <span class="file-size">{{ formatFileSize(uploadedFile.size) }}</span>
                      <span class="file-status">上传成功</span>
                    </div>
                  </div>
                </div>
                <Icon 
                  name="cross" 
                  size="16" 
                  color="#999"
                  class="remove-icon"
                  @click="removeUploadedFile"
                />
              </div>
              
              <!-- 上传进度 -->
              <div v-if="isUploading" class="upload-progress">
                <Icon name="loading" size="16" class="loading-icon" />
                <span>正在上传文件...</span>
              </div>
            </div>
            
            <div class="tips">
              <Icon name="info-o" size="14" color="#1989fa" />
              <span>系统将基于您上传的文件内容自动生成试题，支持单选题、多选题、判断题、简答题等多种题型。</span>
            </div>
            
            <!-- 生成按钮 -->
            <div class="action-buttons">
              <Button 
                type="primary" 
                :loading="isGenerating"
                :disabled="!uploadedFile"
                @click="generateQuestion"
                class="generate-btn"
              >
                <Icon name="notes-o" size="16" />
                {{ isGenerating ? '生成中...' : '生成试题' }}
              </Button>
            </div>
          </div>
          
          <!-- 右侧：预览区域 -->
          <div class="preview-section">
            <div class="section-header">
              <h3>试题预览</h3>
              <Button 
                v-if="htmlContent"
                type="success"
                size="small"
                @click="downloadHtml"
                class="download-btn"
              >
                <Icon name="down" size="14" />
                下载HTML
              </Button>
            </div>
            
            <div class="preview-container">
              <!-- 空状态 -->
              <div v-if="!isGenerating && !htmlContent" class="preview-placeholder">
                <Icon name="notes-o" size="64" color="#c8c9cc" />
                <p>请上传文件并点击生成试题</p>
                <div class="placeholder-features">
                  <p>支持功能：</p>
                  <ul>
                    <li>• 智能内容分析生成试题</li>
                    <li>• 多种题型自动生成</li>
                    <li>• 美观的试题排版</li>
                    <li>• 一键下载HTML试卷</li>
                  </ul>
                </div>
              </div>
              
              <!-- 生成中状态 -->
              <div v-else-if="isGenerating" class="generating-state">
                <Icon name="loading" size="48" color="#1989fa" class="loading-icon" />
                <h4>正在生成试题中...</h4>
                <p>正在分析文档内容并生成试题，请稍候...</p>
              </div>
              
              <!-- HTML预览 -->
              <div v-else-if="htmlContent" class="html-preview">
                <iframe 
                  :srcdoc="htmlContent" 
                  class="html-iframe"
                  frameborder="0"
                  sandbox="allow-same-origin allow-scripts"
                ></iframe>
              </div>
            </div>
          </div>
          
          <!-- 历史记录 -->
          <div v-if="history.length > 0" class="history-section">
            <div class="section-header">
              <h3>历史记录</h3>
              <span class="history-count">{{ history.length }} 条记录</span>
            </div>
            
            <div class="history-list">
              <div 
                v-for="item in history" 
                :key="item.id"
                class="history-item"
                @click="loadFromHistory(item)"
              >
                <div class="history-preview">
                  <iframe 
                    :srcdoc="item.htmlContent" 
                    class="preview-iframe"
                    frameborder="0"
                    sandbox="allow-same-origin allow-scripts"
                  ></iframe>
                </div>
                <div class="history-info">
                  <div class="history-title">{{ item.fileName }}</div>
                  <div class="history-meta">
                    <span class="history-file">{{ formatFileSize(item.fileSize) }}</span>
                    <span class="history-time">{{ formatTimestamp(item.timestamp) }}</span>
                  </div>
                </div>
                <div class="history-actions">
                  <Icon 
                    name="delete-o" 
                    size="16" 
                    color="#ee0a24"
                    class="delete-icon"
                    @click="removeHistoryItem(item, $event)"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, defineProps, computed, onMounted } from 'vue'
  import { showToast, showDialog, Icon, Field, Button } from 'vant'
  import { useQuestionStore } from '@/store/question'
  
  const props = defineProps({
    embed: { type: Boolean, default: false }
  })
  
  const questionStore = useQuestionStore()
  const uploadedFile = ref<any>(null)
  const isUploading = ref(false)
  
  // 计算属性从store获取数据
  const isGenerating = computed(() => questionStore.isGenerating)
  const htmlContent = computed(() => questionStore.currentHtmlContent)
  const history = computed(() => questionStore.history)
  
  // 在组件挂载时加载历史记录
  onMounted(() => {
    questionStore.loadHistoryFromLocalStorage()
  })
  
  const generateQuestion = async () => {
    if (!uploadedFile.value) {
      showToast('请上传文件')
      return
    }
    
    questionStore.setGenerating(true)
    questionStore.setCurrentHtmlContent('')
    
    try {
      const formData = new FormData()
      formData.append('file', uploadedFile.value.file)
      
      const response = await fetch(`${import.meta.env.VITE_BASE_URL}/api/agent/oneclick/question`, {
        method: 'POST',
        body: formData
      })
      
      if (!response.ok) {
        throw new Error(`生成失败: ${response.status}`)
      }
      
      const result = await response.json()
      
      if (result.code !== 0) {
        throw new Error(result.message || '生成失败')
      }
      
      const content = result.data
      questionStore.setCurrentHtmlContent(content)
      
      // 添加到历史记录
      questionStore.addToHistory(
        uploadedFile.value.name,
        uploadedFile.value.size,
        content
      )
      
      showToast('试题生成成功')
    } catch (error) {
      console.error('生成试题失败:', error)
      showToast(error instanceof Error ? error.message : '生成试题失败，请重试')
    } finally {
      questionStore.setGenerating(false)
    }
  }
  
  const downloadHtml = () => {
    if (!htmlContent.value) {
      showToast('没有可下载的试题')
      return
    }
    
    // 创建Blob对象
    const blob = new Blob([htmlContent.value], { type: 'text/html' })
    const url = URL.createObjectURL(blob)
    
    // 创建下载链接
    const a = document.createElement('a')
    a.href = url
    a.download = `试题-${Date.now()}.html`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    
    // 释放URL对象
    URL.revokeObjectURL(url)
    
    showToast('试题下载成功')
  }
  
  // 自定义文件上传处理
  const handleFileSelect = (event: Event) => {
    const target = event.target as HTMLInputElement
    const file = target.files?.[0]
    
    if (!file) return
    
    // 检查文件类型
    const allowedTypes = ['.pdf', '.doc', '.docx', '.txt', '.ppt', '.pptx']
    const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
    
    if (!allowedTypes.includes(fileExtension)) {
      showToast('不支持的文件格式')
      target.value = ''
      return
    }
    
    // 检查文件大小（50MB限制）
    if (file.size > 50 * 1024 * 1024) {
      showToast('文件大小不能超过50MB')
      target.value = ''
      return
    }
    
    uploadedFile.value = {
      file,
      name: file.name,
      size: file.size
    }
    
    target.value = ''
  }
  
  const triggerFileInput = () => {
    const fileInput = document.getElementById('file-input') as HTMLInputElement
    fileInput?.click()
  }
  
  const removeUploadedFile = () => {
    uploadedFile.value = null
  }
  
  const clearAll = () => {
    showDialog({
      title: '清空确认',
      message: '确定要清空所有内容和历史记录吗？',
      showCancelButton: true,
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      confirmButtonColor: '#4080ff',
    }).then(() => {
      uploadedFile.value = null
      questionStore.setCurrentHtmlContent('')
      questionStore.clearHistory()
      showToast('已清空')
    }).catch(() => {})
  }
  
  const loadFromHistory = (item: any) => {
    questionStore.setCurrentHtmlContent(item.htmlContent)
  }
  
  const removeHistoryItem = (item: any, event: Event) => {
    event.stopPropagation()
    showDialog({
      title: '删除确认',
      message: '确定要删除这条历史记录吗？',
      showCancelButton: true,
      cancelButtonText: '取消',
      confirmButtonText: '删除',
      confirmButtonColor: '#ee0a24',
    }).then(() => {
      questionStore.removeHistoryItem(item.id)
      showToast('已删除')
    }).catch(() => {})
  }
  
  const formatTimestamp = (timestamp: number) => {
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN')
  }
  
  const formatFileSize = (size: number) => {
    if (size < 1024) return size + ' B'
    if (size < 1024 * 1024) return (size / 1024).toFixed(1) + ' KB'
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
  </script>
  
  <style scoped lang="scss">
  .step-question {
    width: 100%;
    height: 100%;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    padding: 0;
  }
  
  .question-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 600px;
    background-color: #fff;
    
    .web-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 24px;
      border-bottom: 1px solid #ebeef5;
      background-color: #fff;
      position: sticky;
      top: 0;
      z-index: 100;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      
      .title {
        font-size: 18px;
        font-weight: 500;
        color: #333;
      }
      
      .actions {
        .clear-button {
          display: flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          background-color: #f5f5f5;
          border-radius: 4px;
          color: #606266;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s;
          
          &:hover {
            background-color: #e8e8e8;
          }
        }
      }
    }
    
    .question-content {
      flex: 1;
      padding: 24px;
      overflow-y: auto;
      display: grid;
      grid-template-columns: 1fr 2fr;
      gap: 24px;
      
      .section-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
        
        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
        
        .history-count {
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
          padding: 2px 8px;
          border-radius: 12px;
        }
      }
      
      .input-section {
        .upload-section {
          margin-bottom: 16px;
          
          .custom-upload {
            .upload-area {
              border: 2px dashed #e1e5e9;
              border-radius: 12px;
              padding: 40px 20px;
              text-align: center;
              background: #fafbfc;
              transition: all 0.3s;
              cursor: pointer;
              
              &:hover {
                border-color: #1989fa;
                background: #f0f9ff;
              }
              
              p {
                margin: 12px 0 8px 0;
                font-size: 16px;
                color: #333;
                font-weight: 500;
              }
              
              span {
                display: block;
                font-size: 12px;
                color: #999;
                margin-bottom: 4px;
              }
              
              .size-limit {
                font-size: 12px;
                color: #999;
              }
            }
          }
          
          .uploaded-file {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 16px;
            background: #f0f9ff;
            border: 1px solid #b3d8ff;
            border-radius: 8px;
            
            .file-info {
              display: flex;
              align-items: center;
              gap: 12px;
              flex: 1;
              
              .file-details {
                .file-name {
                  font-size: 14px;
                  color: #333;
                  font-weight: 500;
                  margin-bottom: 2px;
                }
                
                .file-meta {
                  .file-size {
                    font-size: 12px;
                    color: #666;
                  }
                  
                  .file-status {
                    font-size: 12px;
                    color: #52c41a;
                  }
                }
              }
            }
            
            .remove-icon {
              cursor: pointer;
              transition: color 0.2s;
              padding: 4px;
              border-radius: 4px;
              
              &:hover {
                color: #ee0a24;
                background: rgba(238, 10, 36, 0.1);
              }
            }
          }
          
          .upload-progress {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 16px;
            background: #f0f9ff;
            border-radius: 8px;
            margin-top: 12px;
            
            .loading-icon {
              animation: rotate 1s linear infinite;
              margin-right: 8px;
            }
            
            span {
              font-size: 14px;
              color: #666;
            }
          }
        }
        
        .tips {
          display: flex;
          align-items: flex-start;
          gap: 8px;
          padding: 12px;
          background: #f0f9ff;
          border-radius: 8px;
          margin-bottom: 16px;
          font-size: 13px;
          color: #666;
          line-height: 1.5;
        }
        
        .action-buttons {
          .generate-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #1989fa, #40a9ff);
            border: none;
            border-radius: 8px;
            font-weight: 500;
            font-size: 15px;
            width: 100%;
            justify-content: center;
            
            &:hover:not(:disabled) {
              background: linear-gradient(135deg, #1670cc, #369eea);
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
            }
            
            &:disabled {
              opacity: 0.6;
            }
          }
        }
      }
      
      .preview-section {
        .preview-container {
          border: 2px solid #e1e5e9;
          border-radius: 12px;
          min-height: 400px;
          background: #fafbfc;
          overflow: hidden;
          
          .preview-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 400px;
            text-align: center;
            color: #666;
            padding: 20px;
            
            p {
              margin: 16px 0;
              font-size: 14px;
            }
            
            .placeholder-features {
              margin-top: 20px;
              
              p {
                font-size: 13px;
                color: #888;
                margin-bottom: 8px;
              }
              
              ul {
                text-align: left;
                display: inline-block;
                font-size: 12px;
                color: #999;
                line-height: 1.8;
                
                li {
                  margin-bottom: 4px;
                }
              }
            }
          }
          
          .generating-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 400px;
            text-align: center;
            padding: 20px;
            
            .loading-icon {
              animation: rotate 1s linear infinite;
              margin-bottom: 16px;
            }
            
            h4 {
              margin: 0 0 8px 0;
              color: #1989fa;
              font-size: 16px;
            }
            
            p {
              margin: 8px 0;
              color: #666;
              font-size: 14px;
            }
          }
          
          .html-preview {
            width: 100%;
            height: 100%;
            min-height: 400px;
            
            .html-iframe {
              width: 100%;
              height: 100%;
              min-height: 400px;
              border: none;
            }
          }
        }
        
        .download-btn {
          display: flex;
          align-items: center;
          gap: 6px;
          background: #52c41a;
          border: none;
          
          &:hover {
            background: #389e0d;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
          }
        }
      }
      
      .history-section {
        grid-column: 1 / -1;
        margin-top: 24px;
        
        .history-list {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
          gap: 16px;
          
          .history-item {
            border: 1px solid #e1e5e9;
            border-radius: 12px;
            padding: 16px;
            cursor: pointer;
            transition: all 0.2s;
            background: #fff;
            position: relative;
            
            &:hover {
              border-color: #1989fa;
              box-shadow: 0 2px 8px rgba(25, 137, 250, 0.15);
              transform: translateY(-2px);
            }
            
            .history-preview {
              width: 100%;
              height: 120px;
              overflow: hidden;
              border-radius: 8px;
              background: #f8f9fa;
              margin-bottom: 12px;
              
              .preview-iframe {
                width: 100%;
                height: 100%;
                pointer-events: none;
              }
            }
            
            .history-info {
              .history-title {
                font-size: 14px;
                font-weight: 600;
                color: #333;
                margin-bottom: 4px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
              
              .history-meta {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                font-size: 11px;
                
                span {
                  padding: 2px 6px;
                  border-radius: 4px;
                  background: #f5f5f5;
                  color: #666;
                  
                  &.history-file {
                    background: #fff7e6;
                    color: #fa8c16;
                  }
                  
                  &.history-time {
                    background: #f5f5f5;
                    color: #999;
                  }
                }
              }
            }
            
            .history-actions {
              position: absolute;
              top: 12px;
              right: 12px;
              
              .delete-icon {
                padding: 4px;
                cursor: pointer;
                border-radius: 4px;
                transition: all 0.2s;
                
                &:hover {
                  background: rgba(238, 10, 36, 0.1);
                }
              }
            }
          }
        }
      }
    }
    
    &.embed {
      .web-header {
        position: static !important;
        box-shadow: none;
      }
    }
    
    @media (max-width: 1200px) {
      .question-content {
        grid-template-columns: 1fr;
        gap: 16px;
      }
      
      .history-section .history-list {
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      }
    }
  }
  
  @keyframes rotate {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
  }
  </style> 